import streamlit as st
import pandas as pd

if 'counter' not in st.session_state:
        st.session_state.counter = 0
if 'panels' not in st.session_state:
        st.session_state.panels = []
if 'point_config' not in st.session_state:
        st.session_state.point_config = []
if 'file_content' not in st.session_state:
        st.session_state.file_content = ""

@st.dialog("Cast your vote")
def vote(item):
    st.write(f"Why is {item} your favorite?")
    model_name = st.text_input("model name")
    model_version = st.text_input("model version")
    if st.button("Submit"):
        if model_name.strip() == "":
                st.error("need input model name")
        elif model_version.strip() == "":
                st.error("need input model version")
        else:
            st.session_state.file_content = "name:"+model_name + '\n'
            st.session_state.file_content = st.session_state.file_content + "ver:"+model_version + '\n'
            st.session_state.vote = {"name": model_name,"version":model_version}
            st.rerun()



def p_c():
        # key
        key = st.text_input("point name",placeholder="Ua",disabled=False)


        datatype = st.selectbox(
            "data type:",
            ("u16","i16","u32","i32","f32","d64","enum16","datetime"),
        )
        if datatype == "enum16":
            # 模拟学生成绩数据
            student_grades = pd.DataFrame(
                {
                    "Real Value": [],
                    "Cloud Value": [],
                }
            )
            # 定义列配置
            column_config = {
                "Real Value": {"label": "Real Value"},
                "Cloud Value": st.column_config.NumberColumn(
                    label="Cloud Value",
                    min_value=0,
                    max_value=150,
                    format="%d",
                ),
            }
            # 使用st.data_editor展示和编辑学生成绩，并应用列配置
            st.title("MAP")
            edited_grades = st.data_editor(
                student_grades,
                column_config=column_config,
                num_rows="dynamic",
            )
            # 显示编辑后的数据（用于确认更改）
            st.write("编辑后的MAP:")
            st.dataframe(edited_grades)


        regaddr = st.text_input("register address",placeholder="need hex string like : 00FF",disabled=False)


        regcnt = st.number_input("register count:",min_value=1,max_value=2,step=1,value=1,format="%d")


        opt = ["***0x03***","***0x10***","***0x06***",":rainbow[0x03 and 0x10]",":rainbow[0x03 and 0x06]"]
        funcode = st.radio(
            "Function Code",
            opt,
            index=0
        )
        index = opt.index(funcode)
        if index == 0:
            read_code = "03"
            write_code = "0"
        elif index == 1:
            read_code = "0"
            write_code = "10"
        elif index == 2:
            read_code = "0"
            write_code = "06"
        elif index == 3:
            read_code = "03"
            write_code = "10"
        elif index == 4:
            read_code = "03"
            write_code = "06"


        unit = st.selectbox(
            "unit:",
            ("1000","100","10","1","0.1","0.01","0.001","0.000001"),
            index=5
        )
        st.write("You unit",unit)




        if datatype == "enum16":
            ####
            start_bit = st.number_input("start_bit",min_value=0,max_value=15,step=1,value=1,format="%d")
            st.write("The start bit is",start_bit)
            bit_len = st.number_input("bit_len",min_value=0,max_value=15,step=1,value=1,format="%d")
            st.write("The bit len is",bit_len)



        timeout = st.number_input("Modbus frame timeout:",min_value=300,max_value=3000,step=50,value=300,format="%d")
        st.write("The timeout is",timeout)



        point_interval = st.number_input("Modbus point interval:",min_value=10,max_value=500,step=10,value=20,format="%d")
        st.write("The point interval is",point_interval)




        shadow_flow_rank = st.selectbox(
            "point data rank:",
            ("1","2","3","4"),
        )
        if shadow_flow_rank != "rank 4":
            with st.form("percent"):
                shadow_flow_percent = st.slider("Form slider",min_value=0,max_value=100,value=5,step=5,format="%d")
                submitted = st.form_submit_button("Submit")
                if submitted:
                    st.write("slider",shadow_flow_percent)



        shadow_flow_threshold = st.number_input("Modbus shadow_flow_threshold:",min_value=10,max_value=5000,step=50,value=25,format="%d")
        st.write("The shadow_flow_threshold is",shadow_flow_threshold)

        agree = st.checkbox("block read point")
        shadow_flow_read_mode = 0
        if agree:
            st.write("It's a block read")
            shadow_flow_read_mode = 1

        submitted = st.button("Submit")
        if submitted:
            if key.strip() == "":
                st.error("need input point name")
            elif regaddr.strip() == "":
                st.error("need input hex regaddr")
            else:
                if(shadow_flow_read_mode == 1):
                    result_string = f"- {key};{datatype};{regaddr};{regcnt};[{read_code},{write_code}];;;;{unit};;;{timeout};{point_interval};{shadow_flow_rank};{shadow_flow_percent};{shadow_flow_threshold};{shadow_flow_read_mode};;\n"
                else:
                    result_string = f"- {key};{datatype};{regaddr};{regcnt};[{read_code},{write_code}];;;;{unit};;;{timeout};{point_interval};{shadow_flow_rank};{shadow_flow_percent};{shadow_flow_threshold};;;\n"
                st.write(result_string)
                st.session_state.point_config.append({"result_string": result_string})
                st.session_state.file_content = st.session_state.file_content + result_string
                print("hehehda1")
                st.session_state.counter += 1
                new_panel_id = len(st.session_state.panels) + 1  # 使用列表长度加1作为新面板的ID（确保唯一性）
                st.session_state.panels.append({'id': new_panel_id})  # 将新面板信息添加到会话状态中
                st.rerun()


@st.dialog("point_config")
def point_config():
    return p_c()


# Point Config 页面函数
def point_config_page():
    with st.expander("ex0"):
        with st.container():
            st.title("Point Config0")
            # 这里可以添加更多的配置选项
            key = st.text_input("Point name", "Enter a name",None,key=1)
            st.write(f"You entered point name: {key}")
    with st.expander("ex1"):
        with st.container():
            st.title("Point Config1")
            # 这里可以添加更多的配置选项
            key = st.text_input("Point name", "Enter a name",None,key=2)
            st.write(f"You entered point name: {key}")
    with st.expander("ex2"):
        with st.container():
            st.title("Point Config2")
            # 这里可以添加更多的配置选项
            key = st.text_input("Point name", "Enter a name",None,key=3)
            st.write(f"You entered point name: {key}")
    with st.expander("ex3"):
        with st.container():
            # key
            key = st.text_input("point name","like Ua",None,key=4)
            datatype = st.selectbox(
                "data type:",
                ("u16","u32","i16","i32","enum16","datetime"),
            )
            if datatype == "enum16":
                # 模拟学生成绩数据
                student_grades = pd.DataFrame(
                    {
                        "Real Value": [],
                        "Cloud Value": [],
                    }
                )
                # 定义列配置
                column_config = {
                    "Real Value": {"label": "Real Value"},
                    "Cloud Value": st.column_config.NumberColumn(
                        label="Cloud Value",
                        min_value=0,
                        max_value=150,
                        format="%d",
                    ),
                }
                # 使用st.data_editor展示和编辑学生成绩，并应用列配置
                st.title("MAP")
                edited_grades = st.data_editor(
                    student_grades,
                    column_config=column_config,
                    num_rows="dynamic",
                )
                # 显示编辑后的数据（用于确认更改）
                st.write("编辑后的MAP:")
                st.dataframe(edited_grades)


            regaddr = st.text_input("register address","like 0x0001")


            regcnt = st.number_input("register count:",min_value=1,max_value=2,step=1,value=1,format="%d")


            opt = ["***0x03***","***0x10***","***0x06***",":rainbow[0x03 and 0x10]",":rainbow[0x03 and 0x06]"]
            funcode = st.radio(
                "Function Code",
                opt,
                index=0
            )
            index = opt.index(funcode)
            if index == 0:
                read_code = "03"
                write_code = "0"
            elif index == 1:
                read_code = "0"
                write_code = "10"
            elif index == 2:
                read_code = "0"
                write_code = "06"
            elif index == 3:
                read_code = "03"
                write_code = "10"
            elif index == 4:
                read_code = "03"
                write_code = "06"


            unit = st.selectbox(
                "unit:",
                ("1000","100","10","1","0.1","0.01","0.001","0.000001"),
                index=5
            )
            st.write("You unit",unit)




            if datatype == "enum16":
                ####
                start_bit = st.number_input("start_bit",min_value=0,max_value=15,step=1,value=1,format="%d")
                st.write("The start bit is",start_bit)
                bit_len = st.number_input("bit_len",min_value=0,max_value=15,step=1,value=1,format="%d")
                st.write("The bit len is",bit_len)



            timeout = st.number_input("Modbus frame timeout:",min_value=300,max_value=3000,step=50,value=300,format="%d")
            st.write("The timeout is",timeout)



            point_interval = st.number_input("Modbus point interval:",min_value=10,max_value=500,step=10,value=20,format="%d")
            st.write("The point interval is",point_interval)




            shadow_flow_rank = st.selectbox(
                "point data rank:",
                ("1","2","3","4"),
            )
            if shadow_flow_rank != "rank 4":
                with st.form("percent"):
                    shadow_flow_percent = st.slider("Form slider",min_value=0,max_value=100,value=5,step=5,format="%d")
                    submitted = st.form_submit_button("Submit")
                    if submitted:
                        st.write("slider",shadow_flow_percent)



            shadow_flow_threshold = st.number_input("Modbus shadow_flow_threshold:",min_value=10,max_value=5000,step=50,value=25,format="%d")
            st.write("The shadow_flow_threshold is",shadow_flow_threshold)

            agree = st.checkbox("block read point")
            if agree:
                st.write("It's a block read")
                shadow_flow_read_mode = 1

            submitted = st.button("Submit")
            if submitted:
                result_string = f"- {key};{datatype};{regaddr};{regcnt};[{read_code},{write_code}];{unit};{timeout};{point_interval};{shadow_flow_rank};{shadow_flow_percent};{shadow_flow_threshold};1;;"
                st.write(result_string)



# 函数：显示单个面板及其删除按钮
def display_panel(panel_id, panel_name):
    with st.expander(panel_name):
        st.title(f"Point Config {panel_id}")
        # 这里可以添加更多的配置选项

        # 删除按钮
        if st.button("Delete",key=panel_id, icon="🗑️"):
            # 从会话状态中移除面板信息
            st.session_state.panels = [p for p in st.session_state.panels if p['id'] != panel_id]
            # 由于Streamlit的页面渲染机制，我们需要重新加载页面或触发某种刷新来更新UI
            # 这里我们使用st.experimental_rerun()来重新运行整个脚本（注意：这是实验性功能，未来可能会更改）
            # 另一种方法是使用回调或事件系统来更新UI，但这通常涉及更复杂的逻辑和状态管理
            # 对于简单应用，重新运行脚本通常足够
            # st.experimental_rerun()  # 注意：这将重新加载整个页面，可能会导致用户体验不佳








left, middle, right = st.columns(3)
# Point Config 页面函数
def point_display(content):
    with st.expander(content):
        with st.container():
            st.title("Point Config0")
            # 这里可以添加更多的配置选项
            key = st.text_input("Point name", "Enter a name",None,key=1)
            st.write(f"You entered point name: {key}")


i = 0
if "vote" not in st.session_state:
    # st.write("Vote for your favorite")
    if st.button("Create New Model", icon="➕", use_container_width=True):
        vote("A")
else:
    f"Model name: {st.session_state.vote['name']}"
    f"Version: {st.session_state.vote['version']}"
    if right.button("Create New point", icon="➕", use_container_width=True):
        point_config()
    for str in st.session_state.point_config:
        print(str)
    # 显示所有面板
    for panel in st.session_state.panels:
        panel_id = panel['id']
        panel_name = panel.get('name', f"Untitled Panel {panel_id}")  # 假设面板有一个可选的名称属性，默认为"Untitled Panel"加上ID
        panel_name = st.session_state.point_config[panel_id - 1]['result_string']
        print(panel_id)
        print("nnnnnn"+panel_name)
        display_panel(panel_id, panel_name)
        # # if "point_config" in st.session_state:
        # print("hehehda")
        # point_config_page()
    print(st.session_state.file_content)
    text_contents = '''Jack's model file'''
    middle.download_button(
        "general file",
        st.session_state.file_content,
        file_name="QK.chintm")